package com.example.myapp.Fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapp.ADO.PostAdapter;
import com.example.myapp.ADO.UpdateAppManager;
import com.example.myapp.Activity.Main;
import com.example.myapp.Listviewloading.MyFooterAdapter;
import com.example.myapp.Listviewloading.MyHeaderAdapter;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Defaulticon;
import com.example.myapp.R;
import com.example.myapp.Model.Article;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnFooterRefreshListener;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import java.lang.invoke.MutableCallSite;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

//import android.support.v4.app.Fragment;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SHOW_TEXT = "text";
    private ShapeLoadingDialog shapeLoadingDialog;
    private String mContentText;
    private   List<Article>  articles;
    private PostAdapter postAdapter;
    private RecyclerView recyclerView;
    private UltimateRefreshView mUltimateRefreshView;
    private int page=0;
    private   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String updatatime="";
    private    TextView text_pao;
    private TextView  text_pao2;


    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_SHOW_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }

    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                   // largeALL("2020-07-01 10:30:00");
                    getNew5Post();
                    } break;
                case 2:
                    BmobQuery<Defaulticon> bmobQuery = new BmobQuery<Defaulticon>();
                    bmobQuery.getObject("nlS2IIIO", new QueryListener<Defaulticon>() {
                        @Override
                        public void done(Defaulticon object,BmobException err) {
                            if (err == null) {
                                text_pao.setText(""+object.getMsg());
                                text_pao2.setText(""+object.getMsg2());
                            }}
                    });
                    break;
                }
            }

    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mContentText = getArguments().getString(ARG_SHOW_TEXT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, viewGroup, false);
        recyclerView = rootView.findViewById(R.id.recyclerView);
           text_pao= rootView.findViewById(R.id.text_pao);
          text_pao2= rootView.findViewById(R.id.text_pao2);
        mUltimateRefreshView = (UltimateRefreshView)rootView.findViewById(R.id.refreshView);
        /**部下拉刷新*/
        mUltimateRefreshView.setBaseHeaderAdapter(new MyHeaderAdapter(getActivity()));
        /**底部上拉加载*/
        mUltimateRefreshView.setBaseFooterAdapter(new MyFooterAdapter(getActivity()));
        /**头部下拉刷新事件*/
        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {
                page = 0;
                /**
                 * 某个时间后
                 */
                try {
                    String createdAt = updatatime;
                    Date date = new Date(System.currentTimeMillis());
                    updatatime= simpleDateFormat.format(date);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createdAtDate = sdf.parse(createdAt);
                    BmobDate bmobCreatedAtDate = new BmobDate(createdAtDate);
                    BmobQuery<Article> categoryBmobQuery = new BmobQuery<>();
                    categoryBmobQuery.addWhereGreaterThan("createdAt", bmobCreatedAtDate);
                    categoryBmobQuery.setLimit(5); // 限制最多10条数据结果作为一页
                    categoryBmobQuery.include("author");
                    categoryBmobQuery.order("-orderTime");
                    //判断是否有缓存，该方法必须放在查询条件（如果有的话）都设置完之后再来调用才有效，就像这里一样。
//                    boolean isCache = categoryBmobQuery.hasCachedResult(Posts.class);
//                    if(isCache){//--此为举个例子，并不一定按这种方式来设置缓存策略
//                        categoryBmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);   // 如果有缓存的话，则设置策略为CACHE_ELSE_NETWORK
//                    }else{
//                        categoryBmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);   // 如果没有缓存的话，则设置策略为NETWORK_ELSE_CACHE
//                    }
                    categoryBmobQuery.findObjects(new FindListener<Article>() {
                        @Override
                        public void done(List<Article> object, BmobException e) {
                            if (e == null) {
                                Log.w("aaaa", "刷新条数: "+ object.size());
//                                Toast.makeText(getActivity(),"找到数据条数："+object.size(),Toast.LENGTH_SHORT).show();
                                if(object.size()>0){
                                    //说明有新文章
                                    articles.clear();
                                   getNew5Post();
                                    mUltimateRefreshView.onHeaderRefreshComplete();
                                }else {
                                    mUltimateRefreshView.onHeaderRefreshComplete();
                                }

                            } else {
                                Log.e("BMOB", e.toString());
                            }
                        }
                    });
                }catch (Exception e){

                }

            }
        });
        /**底部上拉加载事件*/
        mUltimateRefreshView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
            @Override
            public void onFooterRefresh(UltimateRefreshView view) {
                page++;
                BmobQuery<Article> query = new BmobQuery<>();
                query.setSkip(page*5); // 忽略前10条数据（即第一页数据结果）
                query.setLimit(5); // 限制最多10条数据结果作为一页
                //包含作者信息
                query.include("author");
                query.order("-orderTime");
                //判断是否有缓存，该方法必须放在查询条件（如果有的话）都设置完之后再来调用才有效，就像这里一样。
                boolean isCache = query.hasCachedResult(Article.class);
                if(isCache){//--此为举个例子，并不一定按这种方式来设置缓存策略
                    query.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);   // 如果有缓存的话，则设置策略为CACHE_ELSE_NETWORK
                }else{
                    query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);   // 如果没有缓存的话，则设置策略为NETWORK_ELSE_CACHE
                }
                query.findObjects(new FindListener<Article>() {
                    @Override
                    public void done(List<Article> object, BmobException e) {
                        if (e == null) {
                            if (object.size()>0){
                                articles.addAll(object);
                                postAdapter.notifyDataSetChanged();
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }else {
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }
                        } else {
                            Log.e("aaaa","查询我的动态失败"+ e.getMessage());
                            mUltimateRefreshView.onFooterRefreshComplete();
                        }
                    }

                });



            }
        });

        handler.sendEmptyMessage(1);
        handler.sendEmptyMessage(2);
        return rootView;
    }




    /**
     * 获取最新8条文章
     */
    private void getNew5Post(){
openLoading();
        Date date = new Date(System.currentTimeMillis());
        updatatime= simpleDateFormat.format(date);
        BmobQuery<Article> query = new BmobQuery<>();
        query.setLimit(5); // 限制最多10条数据结果作为一页
       // query.setSkip(10); // 忽略前10条数据（即第一页数据结果）
        //包含作者信息
        query.include("author");
        query.order("-orderTime");
        query.findObjects(new FindListener<Article>() {
            @Override
            public void done(List<Article> object, BmobException e) {
                if (e == null) {
                    articles=object;
                    if (articles.size()>0){
                        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());//正常listview
                        recyclerView.setLayoutManager(layoutManager);
                        recyclerView.setItemViewCacheSize(500);
                        postAdapter = new PostAdapter(articles, getActivity());
                        recyclerView.setAdapter(postAdapter);

                    }

                } else {
                    Log.e("aaaa","查询我的动态失败"+ e.getMessage());
                }
                closeLoading();
            }


        });
    }



    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(getActivity())
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }



}